[Coding034] LeetCode 061

Rotate List

Ben 2024.03.24

More coding records

Get the knowledge flowing and circulating! :)

目录

本题收获

题目:61. Rotate List

Given the head of a linked list, rotate the list to the right by k places.

 

Example 1:

img

Example 2:

img

Constraints:


代码1(配 · 手绘过程图)

代码解读 | 评价

这个代码的可读性比较差。具体的思想绘制如图。按照思想即可编写代码。

需要注意点是:特殊情况的判定。

  • 什么时候不翻转?

    • 翻转的k次刚好能够整除整个链表的长度,例如,长度为5的链表,翻转0次、5次、10次、15次还是它本身;

    • 链表如果本身的长度是1或者是空,那么也不会翻转。因为1和空任其翻转还是它自己;

  • 翻转的本质是什么?

    • 【原始链表】:①→②→③→④→⑤→⑥→⑦→⑧

    • 【翻转一次】:→①→②→③→④→⑤→⑥→⑦

    • 【翻转二次】:⑦→⑧→①→②→③→④→⑤→⑥

    • 【翻转三次】:⑥→⑦→⑧→①→②→③→④→⑤

    • 就是截断尾巴安装在头部

复杂度分析

image-20240324183131953